import {PageContainer} from '@ant-design/pro-layout';
import {useEffect, useRef, useState} from "react";
import ProTable, {ActionType} from "@ant-design/pro-table";
import {ProFormRadio} from '@ant-design/pro-form';
import {Button, Dropdown, Image, Input, Menu, message, Select, Space, Switch} from "antd";
import {DownOutlined, PlusOutlined} from "@ant-design/icons";
import {

  getUsersList,
  getUserLevel,
  getUserGroup,
  UpdateUserLabel,
  severalUserGroup,
  severalUserLabel,
  getUserLable,
  editUserList

} from "@/services/ant-design-pro/users";
import AddList from "@/pages/user/UserList/components/AddList";
import AddBalance from "@/pages/user/UserList/components/AddBalance";
import AddPerson from "@/pages/user/UserList/components/AddPerson";
import SendMember from '@/pages/user/UserList/components/SendMember';
import SingleUser from "@/pages/user/UserList/components/SingleUser";
import SingleLevel from "@/pages/user/UserList/components/SingleLevel";
import BatchGroup from "@/pages/user/UserList/components/BatchGroup";
import BatchLevel from "@/pages/user/UserList/components/BatchLevel";
import EditUser from "@/pages/user/UserList/components/EditUser";
import Coupon from "@/pages/user/UserList/components/Coupon";

const UserList = () => {

  const [search, setSearch] = useState({})
  const actionRef = useRef<ActionType>();
  const [isShow, setIsShow] = useState(false)
  const {Option} = Select;
  const [balance, setBalance] = useState(false);
  const [person, setPerson] = useState(false);
  const [userSearch, setUserSearch] = useState({status: 1, include: 'userValue,userlabel'})
  const [level, setLevel] = useState([])
  const [group, setGroup] = useState([])
  const [label,setLabel] = useState([])
  const [optionValues, setOptionValues] = useState({})
  const [keys, setKeys] = useState({})
  const [isSend,setIsSend] = useState(false)
  const [isSingle,SetIsSingle] = useState(false)
  const [isLevel,setIsLevel] = useState(false)
  const [id,setId] = useState(null)
  const [isLabel,setIsLabel] = useState([])
  const [isBatch,setIsBatch] = useState(false)
  const [batchStatus,setBatchStatus] = useState([])
  const [isBatchLevel,setIsBatchLevel] = useState(false)
  const [isBatchLevelStatus,setIsBatchLevelStatus] = useState([])
  const [isShowUser,setIsShowUser] = useState(false)
  const [isEditUser,setIsEditUser] = useState({})
  const [coupon,setCoupon] = useState(false)

  // 在菜单之前显示
  const selectBefore = (
    <Select onChange={(value) => {
      console.log(value);
      setOptionValues({...optionValues, value})
      setKeys(value)
    }} defaultValue="全部" className="select-before">
      <Option value="user_id">UID</Option>
      <Option value="phone">手机号</Option>
      <Option value="nickname">用户昵称</Option>
    </Select>
  );

  useEffect(async () => {
    // 用户等级搜索下拉
    const dataList = await getUserLevel();
    // 用户分组搜索下拉
    const groupList = await getUserGroup();
    // 用户标签列表搜索下拉
    const userLabel = await getUserLable()

    setLevel(dataList.data);
    setGroup(groupList.data);
    setLabel(userLabel.data)
  }, [])

  const columns = [
    {
      title: '用户搜索',
      hideInTable: true,
      hideInForm: false,
      renderFormItem: () => [
        <Space>
          <Input
            onChange={(e) => {
              let item = {}
              item[keys] = e.target.value
              setOptionValues(item)
            }}
            addonBefore={selectBefore}
            placeholder='请输入'/>
        </Space>
      ]
    },
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
      align: 'center',
      width: 100,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      search: false,
      align: 'center',
      render: (_, record) => {
        return (
          <Image
            width={50}
            src={record.avatar}
          />
        );
      }
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      search: false,
      align: 'center',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      align: 'center',
      valueEnum: {
        '1': {text: '男', status: 'Default'},
        '0': {text: '女', status: 'Processing'}
      },
    },
    {
      title: '付费会员',
      dataIndex: 'is_member',
      align: 'center',
      width: 100,
      valueEnum: {
        '1': {text: '是', status: 'Default'},
        '0': {text: '否', status: 'Processing'}
      },
    },
    {
      title:'推广资格',
      dataIndex: 'is_extension',
      align:'center',
      search:false,
      render:(_,record)=>
        <Switch
          checkedChildren="有资格"
          unCheckedChildren="无资格"
          defaultChecked={record.is_extension}
          onChange={async ()=>{

            message.success('操作成功！')
            // 刷新表格
            actionRef.current?.reload();

          }}
        />
    },
    {
      title: '用户等级',
      dataIndex: 'level',
      align: 'center',
      width: 100,
      renderFormItem: () => {
        return (
          <Select style={{width: '100%'}} onSelect={(value) => {
            console.log(value);
          }}>
            <Option key={0} value={0}>全部</Option>
            {
              level.map((item) => {
                return <Option key={item.id} value={item.id}>{item.name}</Option>
              })
            }
          </Select>
        )
      },
    },
    {
      title: '用户标签',
      align: 'center',
      render:(_,record)=>{
        return (
        record.userlabel.data.map(item=>{
          return  <div>{item.label_name}</div>

        })
        )
      },
      renderFormItem:()=>{
        return (
          <Select style={{width: '100%'}} onChange={(value)=>{
            console.log(value)
          }
          }>
            <Option key={0} value={0}>全部</Option>
            {
              label.map((item) => {
                return <Option key={item.id} value={item.id}>{item.label_name}</Option>
              })
            }
          </Select>
        )
      }
    },
    {
      title: '用户分组',
      dataIndex: 'group_id',
      align: 'center',
      width: 100,
      render:(_,record)=>{
        return (
          <span>{record.catrgory.nickname}</span>
        )
      },
      renderFormItem: () => {
        return (
          <Select style={{width: '100%'}} onChange={(value)=>{
            console.log(value)
          }
          }>
            <Option key={0} value={0}>全部</Option>
            {
              group.map((item) => {
                return <Option key={item.id} value={item.id}>{item.nickname}</Option>
              })
            }
          </Select>
        )
      },
    },
    {
      title: '下单次数',
      dataIndex: 'pay_count',
      hideInForm: false,
      align: 'center',
      valueEnum: {
        all: {text: '全部', status: 'Default'},
        close: {text: '0次以上', status: 'close'},
        running: {text: '1次以上', status: 'running'},
        error: {text: '2次以上', status: 'error'},
        online: {text: '3次以上', status: 'online'},
        porty: {text: '4次以上', status: 'porty'},
        popes: {text: '5次以上', status: 'popes'},
      },
    },
    {
      title: '国家',
      dataIndex: 'country',
      align: 'center',
      valueEnum: {
        '1': {text: '外国', status: 'Default'},
        '0': {text: '中国', status: 'Processing'},
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      search: false,
      align: 'center',
      width: 100,
    },
    {
      title: '用户类型',
      dataIndex: 'user_type',
      hideInForm: false,
      search: false,
      align: 'center',
      width: 100,
    },
    {
      title: '余额',
      dataIndex: 'balance',
      align: 'center',
      search: false,
    },
    {
      title:'用户备注',
      dataIndex: 'remark',
      search: false,
      align: 'center',
      width:270
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (text, record, _, _action) => [
        <a
          key="editable"
          onClick={()=>{editUser(record)}}
        >
          编辑
        </a>,
        <Dropdown key={'menu'} overlay={menu(record)}>
          <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
            更多<DownOutlined/>
          </a>
        </Dropdown>
      ],
    },
    {
      title: '访问情况',
      dataIndex: 'qing',
      hideInTable: true,
      hideInForm: false,
      valueEnum: {
        all: {text: '全部', status: 'Default'},
        // close: { text: '中国', status: 'close' },
        running: {text: '时间段未访问', status: 'Processing'},
        error: {text: '时间段访问过', status: 'error'},
        online: {text: '首次访问', status: 'online'},
      },
    },
    {
      title: '访问时间',
      dataIndex: 'createdAtRange',
      valueType: 'dateRange',
      hideInTable: true,
      hideInForm: false,
    },
    {
      title: '身份',
      dataIndex: 'is_promoter',
      hideInForm: false,
      hideInTable: true,
      renderFormItem: () => [
      <ProFormRadio.Group
          name="is_promoter"
          radioType="button"
          options={[
            {label: '全部', value: '1,0',},
            {label: '推广员', value: '1',},
            {label: '普通用户', value: '0',},
          ]}
        />
      ]
    },
  ];

  // 添加用户
  const addList = () => {
    setIsShow(true)
  }

  // 编辑用户
  const editUser = (record)=>{
    setIsEditUser(record)
    setIsShowUser(true)
  }

  // 给账户余额一个点击事件
  const addBalance = () => {
    setBalance(true)
  }

  // 赠送会员
  const send=()=>{
    setIsSend(true)
  }

  // 修改上级推广人
  const addPerson = () => {
    setPerson(true)
  }

  // 设置单个用户分组
  const single = ()=>{
    SetIsSingle(true)
  }

  // 设置批量分组
  const batch =(selectedRows)=>{
    setIsBatch(true)
    setBatchStatus(selectedRows.map( item => item.id ))
  }

  // 设置单个标签
  const biaoqian =(record)=>{
    setIsLabel({label_id:record.userlabel.data?.map(item => item.id)})
    setIsLevel(true)
  }

  // 设置批量标签
  const batchLevel=(selectedRows)=>{
    setIsBatchLevelStatus(selectedRows.map(item =>item.id))
    setIsBatchLevel(true)
  }
  // 设置发送优惠券列表
  const batchCoupon=(selectedRows)=>{
    setCoupon(true)
  }
  // 定义下拉菜单栏
  const menu = (record) => {
      return (
        <Menu>
          <Menu.Item key="1">账单详情</Menu.Item>
          <Menu.Item key="2" onClick={addBalance}>积分余额</Menu.Item>
          <Menu.Item key="3" onClick={send}>
            <SendMember isSend={isSend} setIsSend={setIsSend} actionRef={actionRef} record={record.id}/>
          </Menu.Item>
          <Menu.Item key="4" onClick={single}>
            <SingleUser
              divideInto={record.catrgory.nickname}
              isSingle={isSingle} SetIsSingle={SetIsSingle}
              actionRef={actionRef} record={record.id}
            />
          </Menu.Item>
          <Menu.Item key="5"
           onClick={() => {
             setId(record.id)
             biaoqian(record)
          }}>
            设置标签
          </Menu.Item>

          <Menu.Item key="6" onClick={addPerson}>
            <AddPerson person={person} img={record.avatar}/>
          </Menu.Item>
        </Menu>
      )
    }

  return (
    <div>
      <PageContainer
        header={{
          title: '用户列表',
          breadcrumb: {},
        }}
        tabList={[
          {
            tab: '全部',
            key: '1',
          },
          {
            tab: '微信公众号',
            key: '2',
          },
          {
            tab: '微信小程序',
            key: '3',
          },
          {
            tab: 'H5',
            key: '4',
          },
          {
            tab: 'PC',
            key: '5',
          },
          {
            tab: 'APP',
            key: '6',
          }
        ]}
        onTabChange={(key) => {
          switch (key) {
            case '1':
              setSearch({
                ...search, ...{
                  user_type: 'officialAccount,applet,h5,pc,app',
                }
              })

              break;
            case '2':
              setSearch({
                ...search, ...{
                  user_type: 'officialAccount'
                }
              })
              break;
            case '3':
              setSearch({
                ...search, ...{
                  user_type: 'applet'
                }
              })
              break;
            case '4':
              setSearch({
                ...search, ...{
                  user_type: 'h5'
                }
              })
              break;

            case '5':
              setSearch({
                ...search, ...{
                  user_type: 'pc'
                }
              })
              break;
            case '6':
              setSearch({
                ...search, ...{
                  user_type: 'app'
                }
              })
              break;
          }
          actionRef.current?.reload();

        }}
      >
        <ProTable
          columns={columns}
          actionRef={actionRef}
          scroll={{x: 1800}}
          rowSelection={{
            // selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          }}
          tableAlertRender={({selectedRowKeys,selectedRows,onCleanSelected}) => (
            <Space size={30}>
>>>>>>> origin/liyi
              <span>
                已选 {selectedRowKeys.length} 项
                <Button type='primary' style={{marginLeft: 20}} onClick={()=>{batchCoupon(selectedRows)}}>
                  发送优惠券
                </Button>
                <Button type='primary' style={{marginLeft: 20}} onClick={() => {
					batch(selectedRows)
				}}>
                  批量设置分组
                </Button>
                <Button type='primary' style={{marginLeft: 20}} onClick={() => {
					batchLevel(selectedRows)
				}}>
                  批量设置标签
                </Button>
              </span>
            </Space>
          )}
          request={async (params,sort, filter) => {
            const {data, meta} = await getUsersList( {...params,...sort, ...filter, ...search, ...userSearch, ...optionValues} );
            return {
              data,
              success: true,
              total: meta.pagination.total
            }

          }}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          dateFormatter="string"
          toolBarRender={() => [
            <Button key="button" icon={<PlusOutlined/>} type="primary"
                    onClick={addList}>
              添加用户
            </Button>,
          ]}
        />
        <AddList
          isShow={isShow}
          openUser={async (values)=>{
            console.log(values);

            message.success('修改成功！')

            actionRef.current?.reload();
            setIsShow(false)
          }}
          closedUser={()=>{
            setIsShow(false)
          }}
        />
        <AddBalance
          balance={balance}
          setBalance={setBalance}

        />
        {/* 设置标签的列表 */}
        <SingleLevel
          levelInto={isLabel}
          actionRef={actionRef}
          consLevel={isLevel}
          handleOk={async (values)=>{
                await UpdateUserLabel(id,values).then(res=>{
               message.success('修改成功！')

               actionRef.current?.reload();

               setIsLevel(false)
             })
          }}
          leveCancel={()=>{
            setIsLevel(false)
          }}
        />
        {/* 设置批量用户分组 */}
        <BatchGroup
          isBatch={isBatch}
          handleOk={async (values)=>{
            console.log(values);
            await severalUserGroup( {...values,uid:batchStatus});

            message.success('修改成功！')

            actionRef.current?.reload();
            setIsBatch(false)

          }}
          batchCancel={()=>{
            setIsBatch(false)
          }}
        />
        {/* 设置批量标签 */}
        <BatchLevel
          isBatchLevel={isBatchLevel}
          handleOk={async (values)=>{
            await severalUserLabel({...values,uid:isBatchLevelStatus})

            message.success('成功修改！')

            actionRef.current?.reload()

            setIsBatchLevel(false)
          }}
          batchLevel={()=>{
            setIsBatchLevel(false)
          }}
        />
        {/* 编辑用户 */}
        {isShowUser ?
          <EditUser
            record={isEditUser}
            isShowUser={isShowUser}
            open={async (values)=>{
              console.log(values);
              await editUserList(values.id, {...values})
              message.success('成功修改！')

              actionRef.current?.reload()

              setIsShowUser(false)
            }}
            closed={()=>{
              setIsShowUser(false)
            }}
          />
          : null
        }
        {/* 发送优惠券列表 */}
        {
          coupon ?
            <Coupon
              coupon={coupon}
              closeCoupon={()=>{
                setCoupon(false)
              }}
            />
            : null
        }

      </PageContainer>
    </div>

  )
}

export default UserList
